#include "Server.h"

int sock_server;
int sock_client;

int tcp_server_init(in_port_t port)
{

    sock_server = socket(AF_INET ,SOCK_STREAM , 0);
    if (-1 == sock_server)
    {
        ERRLOG("创建套接字失败");
        return -1;
    }
    

    struct sockaddr_in server_addr;
    
    memset(&server_addr , 0 , sizeof(server_addr));

    server_addr.sin_family = AF_INET;

    server_addr.sin_port = htons(port);

    server_addr.sin_addr.s_addr = inet_addr("0.0.0.0");

    if (-1 == bind(sock_server , (struct sockaddr *)&server_addr , sizeof(server_addr)))
    {
        ERRLOG("绑定出错");
        close(sock_server);
        return -2;
    }

    return sock_server;
    
}

int tcp_server_listen(void)
{
    printf("开始监听\n");
    if (-1 == listen(sock_server , 1))
    {
        ERRLOG("监听失败");
        close(sock_server);
        return -3;
    }
    
    sock_client = accept(sock_server ,NULL ,NULL);
    if (sock_client == -1 )
    {
        ERRLOG("连接失败");
        return -4;
    }
    printf("连接成功\n");

    return sock_client;
    
}

void tcp_server_close(void)
{
    close(sock_server);
    printf("关闭成功\n");
    return ;
}